package com.cbank.controller.admin;


import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cbank.constants.Result;
import com.cbank.constants.ResultCode;
import com.cbank.domain.AdminUser;
import com.cbank.service.AdminUserService;
import com.cbank.utils.StringUtil;
import com.cbank.utils.UniqueKeyGenerator;

@Controller
@RequestMapping("/admin")
public class AdminController {
	 Logger logger=Logger.getLogger(AboutUsController.class);
	@Autowired
	private AdminUserService adminUserService;
	
	@RequestMapping(value="/adminLogin",method=RequestMethod.POST,consumes="application/json")
	@ResponseBody
	public Result<AdminUser> adminLogin(AdminUser adminUser,HttpServletResponse resp){
		logger.info("adminLogin start!");
		logger.info("UserName:         "+adminUser.getUserName());
		logger.info("Password:         "+adminUser.getPassword());
		if(StringUtil.isEmpty(adminUser.getUserName())){
			return new Result(ResultCode.ERROR_PASSWORD.getCode(),"账户不允许为空！",null);
		}
		if(StringUtil.isEmpty(adminUser.getPassword())){
			return new Result(ResultCode.ERROR_PASSWORD.getCode(),"密码不允许为空！",null);
		}
		AdminUser user=adminUserService.findByUserNameAndPassword(adminUser);
		if(user==null){
			logger.info("user==null");
			return new Result(ResultCode.ERROR_PASSWORD.getCode(),"用户名或密码错误！",null);
		}else{
			//验证用户名密码正确
			String token=UniqueKeyGenerator.generateToken();
			//更新token
			adminUserService.updateTokenById(token, user.getId());
			//重新查询user
			user=adminUserService.findById(user.getId());
			logger.info("登录成功~");
			return new Result<AdminUser>(ResultCode.SUCCESS.getCode(), "登录成功！", user);
		}
		
	}
	@RequestMapping("/reloadLogin")
	@ResponseBody
	public Result<String> reloadLogin(){
		logger.info("reloadLogin");
		return new Result<>(ResultCode.SUCCESS.getCode(),"该帐号已被其他用户登录！","relogin");
	}

}
